package com.tianbo.elfii.client.common;

import java.io.*;
import java.sql.* ;
import java.net.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
import javax.imageio.*;

import com.tianbo.elfii.client.common.ElfiiCommonUtil.FeedBackType;

/**  <pre>
     <b>类功能描述：</b><pre>
     完成 历史查询第1级 功能要求。
     </pre>
     @version 1.0.1
     @author 高伟 
*/

public class ElfiiCommonHistorySum {

    HistoryListPanel historyPanel;
    JPanel itemPanel;
    JPanel slidePanel;

    int infoBgStartX0;
    int infoBgStartY0;

    int textSelectedNumber;
    int textStartX;
    int textStartY;
    int textStartMaxY;
    int textStartMinY;
    int textLineHeight;

    int clipBgStartX0;
    int clipBgStartY0;
    int slideBgStartX0;
    int slideBgStartY0;
    int slideButtonX;
    int slideButtonY;
    int slideButtonMinY;
    int slideButtonMaxY;

    int dataChoiceIndex;
    int dataSqlLimitNumber=20;
    ArrayList dataViewList;
    ArrayList dataSqlList;

    JFrame mainFrame;
    ElfiiCommonRunInfo runInfo;

    public static int preDataChoiceIndex;
    public static int preSlideButtonY;
    public static int preTextStartY;

    public void setRunInfo(ElfiiCommonRunInfo runInfo){
        this.runInfo=runInfo;
        this.mainFrame=runInfo.getMainFrame();
    }

    public void clearPreSlide(){
        preSlideButtonY=0;
        preDataChoiceIndex=0;
    }

    public void dealBackButton(){
        mainFrame.getContentPane().removeAll();
        ElfiiCommonWelcome welcome = new ElfiiCommonWelcome();
        welcome.setRunInfo(runInfo);
        JPanel p=welcome.createViewPanel();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        mainFrame.getContentPane().add(p,BorderLayout.CENTER);
        mainFrame.validate();
    }

    public void dealOkButton(){
        ElfiiCommonHistoryItem historyItem = new ElfiiCommonHistoryItem();
        historyItem.setRunInfo(runInfo);
        historyItem.clearPreSlide();
        String str=(String) dataSqlList.get(dataChoiceIndex);
        String idStr=str.substring(8,str.length());
        String startDateStr=str.substring(0,8);
        String endDateStr=startDateStr ;

        historyItem.setSqlItems(idStr,startDateStr,endDateStr);
        mainFrame.getContentPane().removeAll();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        mainFrame.getContentPane().add(historyItem.createViewPanel(),BorderLayout.CENTER);
        mainFrame.validate();
    }

    class HistoryListPanel extends JPanel {

        BufferedImage unSelectedImage;
        BufferedImage selectedImage;
        BufferedImage slideBackgroundImage;

        BufferedImage clipBackgroundImage;

        public HistoryListPanel() {
            File f=null;

            try {
                f=new File("resource-common/images/gw/gw_history_01_slide_bg.jpg");
                slideBackgroundImage=ImageIO.read(f);
                f=new File("resource-common/images/history/history_01_unselect.png");
                unSelectedImage=ImageIO.read(f);
                f=new File("resource-common/images/history/history_01_select.png");
                selectedImage=ImageIO.read(f);

                f=new File("resource-common/images/history/history_clipe_bg.png");
                clipBackgroundImage=ImageIO.read(f);

            } catch(Exception e) {System.out.print(e+"   "+f);}

            infoBgStartX0=95;
            infoBgStartY0=25;

            slideBgStartX0=infoBgStartX0+740;
            slideBgStartY0=infoBgStartY0+9;
            slideButtonMinY=slideBgStartY0+113;
            slideButtonMaxY=slideBgStartY0+402;
            slideButtonX=slideBgStartX0+25;
            slideButtonY=slideButtonMinY;

            clipBgStartX0=infoBgStartX0+10;
            clipBgStartY0=infoBgStartY0+20;

            textSelectedNumber=0;

            textLineHeight=98;
            textStartMaxY=clipBgStartY0+5;

            //-textStrings.length-9,其中的9是clip已经显示的内容，余下的内容才是需要向上移的。
            textStartMinY=0-(dataViewList.size()-5)*textLineHeight+textStartMaxY; 
            textStartX=clipBgStartX0;
            textStartY=textStartMaxY; 

            //-如果preSlideButtonY==0，应该作为第一次进入处理
            if (preSlideButtonY!=0){
                slideButtonY=preSlideButtonY;
                textStartY=preTextStartY;
            }
            if (preDataChoiceIndex!=0){
                dataChoiceIndex=preDataChoiceIndex;
            }

        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g ;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
            g2.setColor(Color.black);
            g2.fillRect(0,0,1020,540);
            g2.setColor(Color.white);
            g2.fillRoundRect(infoBgStartX0,slideBgStartY0+4,832,501,75,75);

            g2.setStroke(new BasicStroke(8.0f));
            g2.drawImage(slideBackgroundImage,null,slideBgStartX0,slideBgStartY0);
            g2.setStroke(new BasicStroke(7.0f));
            g2.fillOval(slideButtonX,slideButtonY-25,44,44);
            g2.setClip(clipBgStartX0,clipBgStartY0+6,730,475);

            g2.setFont(new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,28));
            String str,idStr,dateStr;
            int idLen;
            for (int i=0; i<dataViewList.size(); i++) {
                g2.setColor(Color.darkGray);
                if (dataChoiceIndex==i)
                    g2.setColor(ElfiiCommonConstant.Elfii_Blue);
                g2.fillRoundRect(textStartX,textStartY+textLineHeight*i,725,textLineHeight-15,80,80);
                g2.setColor(Color.white);
                str=(String)dataViewList.get(i);

                //ElfiiCommonUtil.dupDot(31-idStr.getBytes().length)
                idStr=str.substring(0,str.length()-10).trim();
                dateStr=str.substring(str.length()-10,str.length());

                idLen=g2.getFontMetrics().stringWidth(idStr);

                g2.drawString(idStr,textStartX+30,textStartY+textLineHeight*i+50);  //+30是因为字体是从下向上画的
                g2.drawString(dateStr,textStartX+530,textStartY+textLineHeight*i+50);  //+30是因为字体是从下向上画的
                for (int j=0; j<(500-idLen)/10-1; j++)
                    g2.drawString(".",textStartX+40+idLen+j*10,textStartY+textLineHeight*i+50);  //+30是因为字体是从下向上画的
            }
            g2.drawImage(clipBackgroundImage,null,clipBgStartX0-10,clipBgStartY0-10);
            
            //-以下内容可以方便地查看每个按钮的坐标是否正确;
            //testXY();
        }
        public Dimension getPreferredSize() {
            return (new Dimension(832,537));
        }
    }

    class HistoryNodataPanel extends JPanel {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g ;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
            g2.setColor(Color.black);
            g2.fillRect(0,0,1020,560);

            g2.setColor(Color.white);
            //g2.fillRoundRect(infoBgStartX0,slideBgStartY0+4,832,501,75,75);

            g2.setFont(new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,32));
            g2.drawString("没有历史数据",410,290);  
        }
        public Dimension getPreferredSize() {
            return (new Dimension(832,537));
        }
    }


    public void createHistoryListPanel(){

        historyPanel=new HistoryListPanel();
        historyPanel.setLayout(new BorderLayout());
        historyPanel.setBackground(Color.black);
        historyPanel.setFocusable(true);
        historyPanel.addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent e) {
                    dealMousePressed(e);
                }
            }
            );

        historyPanel.addMouseMotionListener(new MouseAdapter(){
                public void mouseDragged(MouseEvent e) {
                    dealMouseDragged(e);
                }
            }
            );
    }

    public JPanel createViewPanel(){

        calcHistoryData();

        JPanel p = new JPanel(new BorderLayout()) ;

        JButton okButton=new JButton();
        okButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                	ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                    dealOkButton();
                }
            });

        JButton backButton=new JButton();
        backButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                	ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                    dealBackButton();
                }
            });

        JButton homeButton=runInfo.createHomeButton();
        JPanel topPanel=ElfiiCommonUtil.createTopPanel("历史查询",backButton,homeButton);
        JPanel bottomPanel;
        if (dataViewList.size()>0)
            bottomPanel=ElfiiCommonUtil.createBottomPanelLevelSelect(okButton);
        else
            bottomPanel=ElfiiCommonUtil.createBottomPanelBlank();

        createHistoryListPanel();
        p.setLayout(null);
        p.setBackground(Color.black);
        p.add(topPanel);
        topPanel.setBounds(0,0,1024,100);
        p.add(bottomPanel);
        bottomPanel.setBounds(0,668,1024,100);

        if (dataViewList.size()>0){
            p.add(historyPanel);
            historyPanel.setBounds(0,101,1000,560);
        }else{
            JPanel nodataPanel = new HistoryNodataPanel();
            p.add(nodataPanel);
            nodataPanel.setBounds(0,101,1000,560);
        }
        return p;
    }

    public void dealMouseDragged(MouseEvent e){
        int x=e.getX();
        int y=e.getY();
        if (x>slideButtonX && x<slideButtonX+50 && dataViewList.size()>5) {
            slideButtonY=y;
            if (slideButtonY>slideButtonMaxY)
                slideButtonY=slideButtonMaxY;
            if (slideButtonY<slideButtonMinY)
                slideButtonY=slideButtonMinY;
            textStartY=(int) (textStartMaxY-(textStartMaxY -textStartMinY)*(slideButtonY-slideButtonMinY)/(slideButtonMaxY-slideButtonMinY));

            preSlideButtonY=slideButtonY;
            preTextStartY=textStartY;

            historyPanel.repaint();
        }
    }

    public void dealMousePressed(MouseEvent e){
        int x=e.getX();
        int y=e.getY();
        //System.out.println("clicked x="+x+"   x0="+slideBgStartX0);

        if (x<slideBgStartX0) {

            for (int i=0; i<dataViewList.size(); i++){
                if (y>textStartY+textLineHeight*i && y<textStartY+textLineHeight*(i+1)) {
                	
                	if(preDataChoiceIndex!=i){
                		
                		dataChoiceIndex=i;
                		preDataChoiceIndex=dataChoiceIndex;
                		
                		ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                	}
                	break;
                }
            }
            //System.out.println("labelStartY:"+labelStartY);
            historyPanel.repaint();
        }

        if (x>slideButtonX && x<slideButtonX+50  && dataViewList.size()>5) {
            slideButtonY=y;
            if (slideButtonY>slideButtonMaxY)
                slideButtonY=slideButtonMaxY;
            if (slideButtonY<slideButtonMinY)
                slideButtonY=slideButtonMinY;
            textStartY=(int) (textStartMaxY-(textStartMaxY -textStartMinY)*(slideButtonY-slideButtonMinY)/(slideButtonMaxY-slideButtonMinY));
            //System.out.println("clicked textStartY:"+textStartY);

            preSlideButtonY=slideButtonY;
            preTextStartY=textStartY;

            historyPanel.repaint();
        }
    }

    public void calcHistoryData(){

        Statement st,st2 ;
        ResultSet rs,rs2 ;
        String str;
        dataViewList=new ArrayList<String>();
        dataSqlList=new ArrayList<String>();
        try {
            long startTimeMillis=System.currentTimeMillis();
            st = runInfo.getStatement1();
            st2 = runInfo.getStatement2();

            //str="select distinct trainnerID ,loginDate from TrainningLogin order by loginDate desc limit "+dataSqlLimitNumber ;
            str="select trainnerID ,loginDate,max(loginTime) as lastTime from TrainningLogin group by trainnerID,loginDate order by loginDate desc,lastTime desc limit "+dataSqlLimitNumber ;

            rs=st.executeQuery(str);
            String idStr,dateStr,timeStr;
            boolean isHaveData;
            String dateStrHIJ;
            while(rs.next()){
                idStr=rs.getString("trainnerID");
                dateStr=rs.getString("loginDate");
                dateStrHIJ=dateStr.substring(0,4)+"-"+dateStr.substring(4,6)+"-"+dateStr.substring(6,8);

                //System.out.println("======HIJ: "+dateStrHIJ);

                isHaveData=false;

                str="select trainnerID from TrainningItemAPO where trainnerID='"+idStr+"' and trainningDate='"+dateStr+"'" ;
                rs2=st2.executeQuery(str);
                if (rs2.next()){
                    isHaveData=true;
                }

                str="select id_TrainnerInfoPO from trainningitemfpo where id_TrainnerInfoPO ='"+idStr+"' and trainningDate like '"+dateStrHIJ+"%'" ;
                rs2=st2.executeQuery(str);
                if (rs2.next()){
                    isHaveData=true;
                }

                str="select id_TrainnerInfoPO from trainningitemhpo where id_TrainnerInfoPO ='"+idStr+"' and trainningDate like '"+dateStrHIJ+"%'" ;
                rs2=st2.executeQuery(str);
                if (rs2.next()){
                    isHaveData=true;
                }

                str="select id_TrainnerInfoPO from trainingresultkpo where id_TrainnerInfoPO ='"+idStr+"' and trainningDate like '"+dateStrHIJ+"%'" ;

                rs2=st2.executeQuery(str);
                if (rs2.next()){
                    isHaveData=true;
                }

                str="select id_TrainnerInfoPO from trainningitemlpo where id_TrainnerInfoPO ='"+idStr+"' and trainningDate like '"+dateStrHIJ+"%'" ;
                rs2=st2.executeQuery(str);
                if (rs2.next()){
                    isHaveData=true;
                }

                str="select id_TrainnerInfoPO from trainningitemmpo where id_TrainnerInfoPO ='"+idStr+"' and trainningDate like '"+dateStrHIJ+"%'" ;
                rs2=st2.executeQuery(str);
                if (rs2.next()){
                    isHaveData=true;
                }

                str="select id_TrainnerInfoPO from trainningitemnpo where id_TrainnerInfoPO ='"+idStr+"' and trainningDate like '"+dateStrHIJ+"%'" ;
                rs2=st2.executeQuery(str);
                if (rs2.next()){
                    isHaveData=true;
                }


                if (isHaveData==true){
                    dataSqlList.add(dateStr+idStr); //-未加工数据之前先保存一份
                    idStr=idStr.trim();
                    dateStr=dateStr.substring(0,4)+"/"+dateStr.substring(4,6)+"/"+dateStr.substring(6,8);
                    str=idStr+"    "+dateStr;
                    dataViewList.add(str);
                }

            }

            long endTimeMillis=System.currentTimeMillis();
            //System.out.println("历史查询OK，Time:(1/1000) "+(endTimeMillis-startTimeMillis));

        } catch (Exception e) {System.out.print("init()  "+e);}

    }

}
